package com.cheetah.start.module.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.system.SystemUtil;
import com.cheetah.start.common.config.prop.UploadProp;
import com.cheetah.start.module.system.domain.SysFile;
import com.cheetah.start.module.system.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.UploadedFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@Slf4j
@Component
public class FileServiceImpl implements FileService {

    @Inject("${upload}")
    UploadProp uploadProp;


    @Override
    public SysFile uploadLocal(UploadedFile file) throws IOException {
        String name = file.getName();
        String substring = name.substring(name.lastIndexOf("."));
        String simpleUUID = IdUtil.simpleUUID().substring(10);
        boolean windows = SystemUtil.getOsInfo().isWindows();
        String formatStr;
        if (windows) {
            formatStr = "/yyyy/MM/dd/";
        } else {
            formatStr = "/yyyy/MM/dd/";
        }
        String format = DateUtil.format(new Date(), formatStr);
        String newName = format + simpleUUID + substring;

        String path = uploadProp.getPath();

        SysFile sysFile = new SysFile();

        sysFile.setFileName(simpleUUID + substring);
        sysFile.setFilePath(uploadProp.getHost() + newName);
        sysFile.setFileRealPath(path + newName);
        sysFile.setFileSize(file.getContentSize());

        File fileReal = new File(sysFile.getFileRealPath());
        File parentFile = fileReal.getParentFile();
        if (!parentFile.exists()) {
            boolean mkdirs = parentFile.mkdirs();
            log.info("创建路径:[{}]", mkdirs);
        }

        file.transferTo(fileReal);
        return sysFile;
    }
}
